//
//  CheckAppVersion.m
//  LDY
//
//  Created by 陈兵 on 17/5/18.
//  Copyright © 2017年 陈兵. All rights reserved.
//

#import "CheckAppVersion.h"

@interface CheckAppVersion ()<UIAlertViewDelegate>

@property (nonatomic, strong) NSString * trackUrl;

@end

@implementation CheckAppVersion

+ (CheckAppVersion *)sharedInstance {
    
    static CheckAppVersion * instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[CheckAppVersion alloc] init];
    });
    return instance;
}

- (void)isUpdataApp:(NSString *)appId {
    
    NSString * urlstr = [NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@",appId];
    NSURL * url = [NSURL URLWithString:urlstr];
    NSURLRequest * req = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:req delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
    NSError * error;
    NSDictionary * appInfo = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    NSArray * infoContent = [appInfo objectForKey:@"results"];
    NSString * version = [[infoContent objectAtIndex:0] objectForKey:@"version"];//最新版本号
    NSString * trackViewUrl = [[infoContent objectAtIndex:0] objectForKey:@"trackViewUrl"];//应用程序介绍网址
    NSString * currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
//    NSLog(@"商店版本 = %@",version);
//    NSLog(@"当前版本 = %@",currentVersion);
    self.trackUrl = trackViewUrl;
    if (![version isEqualToString:currentVersion]) {
        UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"更新提示" message:@"检测到新版本，是否去更新？" delegate:self cancelButtonTitle:nil otherButtonTitles:@"去更新", nil];
        [alertView show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex==0) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.trackUrl]];
    }
}

@end
